<template>
  <div class="resource-manager-wp">
    <template v-if="type==='btn'">
      <el-button type="primary" icon='upload' @click.stop.prevent="openManager()" ><slot>上传图片</slot></el-button>
    </template>

    <template v-if="type==='cards'">
      <div class="manager-card-wp">
        <div class="card-list-wp">
          <div class="card-list-img-wp" v-for="(img, index) in selectedList" :key="index">
            <img class="card-list-img" :src="processImg(img.url)">
            <span class="card-list-icon el-icon-circle-close" title="移除" @click.stop.prevent="removeCardsImg(index)"></span>
          </div>
        </div>
        <div v-if="selectedList.length < cardsNum" class="card-upload-wp" style="float: left;" @click.stop.prevent="openManager()">
          <div class="card-upload-img-wp" title="添加图片">
            <i class="card-upload-icon el-icon-plus"></i>
          </div>
        </div>
      </div>
    </template>

    <el-dialog
        :visible.sync="resoureDialogVisible"
        :modal="modal"
        size="large"
        :close-on-click-modal="false"
        custom-class="resource-body-dialog"
    >
      <span slot="title">插入图片</span>

      <div class="resource-body">
        <el-tabs v-model="tabActive" @tab-click="handleTabClick">
          <el-tab-pane label="上传图片" name="upload">
            <div class="tab-content">
              <el-upload
                  ref="uploader"
                  class="upload-manager-wp"
                  name="file"
                  multiple
                  drag
                  accept="image/gif,image/jpeg,image/jpg,image/png"
                  :action="serverUrl"
                  :headers="headers"
                  :data="data"
                  :show-file-list="true"
                  list-type="picture"
                  :before-upload="beforeUpload"
                  :on-progress="handleProgress"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :on-preview="handlePicturePreview"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png/gif文件，且不超过{{limitSize}}</div>
              </el-upload>
            </div>
          </el-tab-pane>
          <el-tab-pane label="图片库" name="list">
            <div class="tab-content">
              <template v-if="list.length >0">
                <div class="img-list-wp">
                  <div class="img-box" v-for="(file,index) in list" :key="file.id">
                    <div class="img-wp" :class="{'selected':isFileSelecetd(file)}" @click.stop.prevent="selectImg(file)">
                      <img :src="processImg(file.img)"/>
                      <span class="selected-box">
                        <i class="el-icon-check"></i>
                      </span>
                    </div>
                    <div class="img-aside">
                      <span @click.stop.prevent="deleteImg(file,index)">删除</span>
                      <span @click.stop.prevent="previewImg(file)">预览</span>
                    </div>
                  </div>
                </div>
                <footer class="img-list-footer">
                  <span class="footer-item">
                    <span>总数</span>
                    <span>{{list.length}}项</span>
                  </span>
                  <span class="footer-item" v-if="type==='cards'">
                    <span>最多可选</span>
                    <span>{{cardsNum}}项</span>
                  </span>
                  <span class="footer-item">
                    <span>已选</span>
                    <span>{{selectedList.length}}项</span>
                  </span>
                  <el-button class="insert-btn"  type="primary" :disabled="selectedList.length<=0" @click.stop.prevent="insertFiles()">插入图片</el-button>
                </footer>
              </template>
              <template v-if="list.length <=0">
                <div class="img-list-none">
                  <span>暂无已上传图片</span>
                  <el-button size="small" @click.stop.prevent="tabActive='upload'">去上传</el-button>
                </div>

              </template>

            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

    </el-dialog>

    <preview-img ref="preview" :list="[]"></preview-img>

  </div>
</template>

<script>
  import {imgFileUpload,albumImgSave,albumImgRemove,albumImgList} from '@/api/other';
  import {host, osshost} from '@/api/util/fetch';
  import PreviewImg from '@/components/previewImg';

  export default {
    name: 'resourceManager', //资源管理
    components:{
      'preview-img':PreviewImg,
    },
    props:{
      type:{ //上传按钮类型:btn,cards
        type:String,
        default:'btn',
      },
      cardsNum:{ //卡片类型最多可以显示几张
        type:Number,
        default:5,
      },
      cardsList:{ //卡片类型默认图片
        type:Array,
        default:()=>{
          return [];
        },
      },
      dir:{ //上传目录
        type:String,
        default: 'default',
      },
      maxSize:{ //最大上传限制,默认1mb:1048576, 5mb:5242880
        type:Number,
        default:1048576,
      },
      modal:{
        type:Boolean,
        default:true,
      }
    },
    data()
    {
      return {
        resoureDialogVisible:false,
        tabActive:'upload',
        headers:{ //服务器接口需要传递token
          'token':this.$store.getters.token,
        },
        data:{ //request data
        },
        pageNum:1,
        pageSize:9999,
        list:[
          /*{
            createTime:0,
            deleted:false,
            fileName:'',
            id:0,
            img:'',
            merchantId:0, //商户id
            updateTime:0,
            version:0,
          }*/
        ],
        selectedList:[],
      }
    },
    computed:{
      serverUrl() //上传接口地址
      {
        return host + 'aliFileUpload/imgFileUpload/' + this.dir;
      },
      limitSize()
      {
        let maxSize = this.maxSize;
        let limit = '';
        if(maxSize >= 1048576)
        {
          limit = (maxSize/1024/1024).toFixed(0) + 'MB';
        }
        else if(maxSize >= 1024)
        {
          limit = (maxSize/1024).toFixed(0) + 'KB';
        }
        else
        {
          limit = maxSize + 'B';
        }
        return limit;
      },
    },
    watch:{
      cardsList(v) //同步已选择的文件
      {
         console.log(v);
         this.selectedList = v;
      }
    },
    methods: {
      removeCardsImg(index) //移除列表图片
      {
        this.selectedList.splice(index,1);
      },
      openManager() //打开上传窗口
      {
        this.getImgList();
        this.resoureDialogVisible = true;

      },
      getImgList() //获取已上传的图片
      {
        let data = {
          pageNum: this.pageNum,
          pageSize:this.pageSize,
          sort:'desc',
        };
        albumImgList(data).then(resp=>{
          let list = resp.data.list || [];
          this.list = list;

        }).catch(err=>{

        });
      },
      handleTabClick(tab, event) //切换上传窗口tab
      {
        if(tab.name==='list')
        {
          this.getImgList();
        }
      },
      isFileSelecetd(file) //判断文件是否选中
      {
         for(let i=0; i< this.selectedList.length; i++)
         {
           if(this.selectedList[i].id === file.id)
           {
             return true;
           }
         }

         return false;
      },
      selectImg(file) //点击文件切换选中状态
      {
        for(let i=0; i<this.selectedList.length; i++)
        {
          //找到已选中的文件，就移除,退出方法
          if(this.selectedList[i].id === file.id)
          {
            this.selectedList.splice(i,1);
            return;
          }
        }

        //循环外说明没有包含，则添加
        //判断是否有添加限制
        if(this.type==='cards' && this.selectedList.length >= this.cardsNum)
        {
          this.$message({
            message: '最多只能选择'+this.cardsNum + '项',
            type: 'warning',
          });
          return;
        }
        else
        {
          file.url = file.img;
          this.selectedList.push(file);
        }
      },
      insertFiles() //插入选中的图片
      {
         let files = [];
         this.selectedList.forEach(item=>{
           files.push({
             id:item.id,
             url: item.url || item.img,
             full_url:osshost + (item.url || item.img),
           });
         });

         this.resoureDialogVisible = false;

         //btn类型清空已选择的文件
         if(this.type==='btn')
         {
           this.selectedList = [];
         }

         this.$emit('insert-success',files);
      },
      beforeUpload(file)
      {
        console.log(file);
        let maxSize = this.maxSize;
        if(file.size > maxSize)
        {
          this.$message({
            message: '超过最大上传限制'+this.limitSize,
            type: 'warning'
          });
          return false;
        }

        return true;
      },
      handleProgress(event,file)
      {
        //console.log('Progress:')
        //console.log(event)
        //console.log(file)
      },
      handleError(err,file)
      {
        this.$message({
          message: err.message,
          showClose: true,
          type: 'error',
          duration: 4000
        });

        this.$refs['uploader'].handleRemove(file);

      },
      handleSuccess(res,file)
      {
        if(res.code !== 200)
        {
          this.handleError(res,file);
        }
        else
        {
          albumImgSave({fileName:file.name,img:res.data}).then(()=>{

          }).catch(err=>{

          });
        }

      },
      handlePicturePreview(file)
      {
        //console.log('Preview:')

        //console.log(file)
      },
      deleteImg(file,index)
      {
        this.$confirm('您将删除图片库中的该图片, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          albumImgRemove({id:file.id}).then((resp)=>{
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.list.splice(index,1);
          }).catch(err=>{

          });

        }).catch(() => {
        });
      },
      previewImg(file)
      {
         this.$refs['preview'].preview(0,[{url:file.img}]);
      },
      processImg(url)
      {
        if(!url || url ==='undefined')
        {
          return '';
        }
        else if(url.indexOf('https://')===0 || url.indexOf('http://')===0)
        {
          return url + '?x-oss-process=image/resize,m_fill,h_100,w_100';
        }
        else
        {
          return osshost + url + '?x-oss-process=image/resize,m_fill,h_100,w_100';
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import "../../styles/mixin";

  .resource-manager-wp
  {
    .manager-card-wp
    {
      @include clearfix;

      .card-list-wp
      {
        float: left;
        margin-right: 12px;

        .card-list-img-wp
        {
          float: left;
          position: relative;
          width: 100px;
          height: 100px;
          border: 1px solid #d1dbe5;

          > .card-list-img
          {
            position: absolute;
            display: block;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            text-align: center;

          }

          > .card-list-icon
          {
            position: absolute;
            right: -8px;
            top: -8px;
            font-size: 20px;
            cursor: pointer;
            color: red;
            overflow: hidden;
          }

          + .card-list-img-wp
          {
            margin-left: 12px;
          }

        }

      }

      .card-upload-wp
      {
        width: 100px;
        height: 100px;
        border: 1px dashed #d1dbe5;
        border-radius: 6px;
        overflow: hidden;

        .card-upload-img-wp
        {
          position: relative;
          width: 100%;
          height: 100%;
          overflow: hidden;
          cursor: pointer;
          text-align: center;

          .card-upload-img
          {
            position: absolute;
            display: block;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            text-align: center;
          }

          .card-upload-icon
          {
            position: absolute;
            font-size: 26px;
            color: #8c939d;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;

            &:before
            {
              display: inline-block;
              vertical-align: middle;
            }

            &:after
            {
              content: "";
              display: inline-block;
              height: 100%;
              vertical-align: middle;
            }
          }

        }

        &:hover
        {
          border-color: #20a0ff;

          .card-upload-img-wp
          {
            .card-upload-icon
            {
              color: #20a0ff;
            }
          }

        }

      }

    }

    .resource-body
    {
      .tab-content
      {
        position: relative;
        min-height: 466px;
      }

      .img-list-wp
      {
        @include clearfix;
        height: 408px;
        overflow-y: auto;

        .img-box
        {
          float: left;
          width: 18%;
          margin: 0 2% 2% 0;

          .img-wp
          {
            position: relative;
            cursor: pointer;
            width: 100%;
            height: 0;
            padding-bottom: 100%;
            border: 1px solid #ccc;
            overflow: hidden;

            > img
            {
              position: absolute;
              left: 0;
              right: 0;
              top: 0;
              bottom: 0;
              width: 100%;
              height: 100%;
            }

            &.selected
            {
              border-color: #20a0ff;

              > .selected-box
              {
                display: block;

                > i
                {
                  display: block;
                  color: #20a0ff;
                }
              }

            }

            > .selected-box
            {
              position: absolute;
              top: 5px;
              right: 5px;
              width: 18px;
              height: 18px;
              border: 1px solid #ddd;
              background: #fff;
              display: none;

              > i
              {
                display: none;
                color: #fff;
              }
            }

            &:hover
            {
              > .selected-box
              {
                display: block;
              }
            }


          }

          .img-aside
          {
            padding: 5px 0;
            text-align: center;

            > span
            {
              display: inline-block;
              padding: 1px 5px;
              cursor: pointer;

              &:hover
              {
                color: #20a0ff;

              }

            }
          }

        }

      }

      .img-list-footer
      {
        @include clearfix;
        padding-top: 20px;
        border-top: 1px solid #d1dbe5;
        position: relative;

        .footer-item
        {
          display: inline-block;
          padding-right: 20px;
        }

        .insert-btn
        {
          float: right;
        }

      }


      .img-list-none
      {
        position: absolute;
        left: 50%;
        top: 40%;
        margin-left: -80px;
        text-align: center;
      }
    }
  }

</style>
<style lang="scss">
  .resource-manager-wp
  {
    .resource-body-dialog
    {
      position: fixed;
      z-index: 9999;
      min-width: 700px;

      .el-dialog__body
      {
        padding: 20px 20px 30px;
      }

      .upload-manager-wp
      {
        width: 100%;

        .el-upload
        {
          width: 100%;

          .el-upload-dragger
          {
            width: 100%;
            height: 300px;

            .el-icon-upload
            {
              font-size: 80px;
              color: #97a8be;
              margin: 80px 0 30px;
            }

          }
        }

        .el-upload-list
        {
          height: 110px;
          overflow-y: auto;
        }

      }

    }
  }
</style>